//
//  WhiteNoise.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/2.
//

import SwiftUI

struct WhiteNoise: View {
    @Environment(\.presentationMode) var presentationMode // 环境变量用于控制视图的返回
    @EnvironmentObject var modelData: ModelData // 使用 EnvironmentObject
    let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 3)
    @EnvironmentObject var audioPlayer: AudioPlayer
    
    var body: some View {
        VStack {
            ScrollView {
                LazyVGrid(columns: columns, spacing: 20) {
                    ForEach(modelData.noises.indices, id: \.self) { index in
                        AudioItem(noise: modelData.noises[index], index: index) { selectedNoise, selectedIndex in
                            self.onSelectedNoiseAction(noise: selectedNoise, index: selectedIndex)
                        }
                    }
                }
                .padding()
            }
        }
        .navigationTitle("白噪音")
        .navigationBarBackButtonHidden(true) // 隐藏默认的返回按钮
        .toolbar {
            // Add a custom back button
            ToolbarItem(placement: .topBarLeading) {
                Button(action: {
                    self.audioPlayer.stopSound()
                    presentationMode.wrappedValue.dismiss()
                }, label: {
                    Image(systemName: "chevron.left")
                        .font(.title2)
                        .foregroundColor(.primary)
                })
            }
        }
        .onAppear {
            if let noise = modelData.currentSelectedNoise,
               noise.id > 1 {
                self.audioPlayer.playSound(file: noise.fileName)
            }
        }
        .onDisappear {
            self.audioPlayer.stopSound()
        }
    }
    
    private func onSelectedNoiseAction(noise: Noise, index: Int) {
        // 非无声音时，播放白噪音
        if (noise.id > 1) {
            self.audioPlayer.stopSound()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                self.audioPlayer.playSound(file: noise.fileName)
            }
        } else {
            self.audioPlayer.stopSound()
        }
    }
}

#Preview {
    NavigationView {
        WhiteNoise()
    }
}
